/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view.Cliente;

import cliente.ConexaoCliente;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;

/**
 *
 * @author natan
 */
public class JanelaChat extends javax.swing.JFrame {

    private static JanelaChat chat;
    private ConexaoCliente cliCon;
    private String msgNova, msgAnterior;
    private DefaultListModel lista_online;

    public JanelaChat(ConexaoCliente cliCon) {
        this.cliCon = cliCon;
        chat = this;

        initComponents();
        campo_msg.requestFocusInWindow(); // posiciona cursor sobre a caixa de mensagem
        lista_online = new DefaultListModel();
        listaPessoasOnline.setModel(lista_online);
        cliCon.criaThreadAtualiza();
        cliCon.criaThreadSinal();
        /*
        lista_online.addElement("funfou");
        lista_online.addElement("certo");
        lista_online.addElement("Maluco");*/
        areaMSGs.append("Ola, seja bem vindo ");
        
    }

    public static JanelaChat getChat() {
        return chat;
    }

    public void AtualizaLista(String temp) {
        int a = Integer.parseInt(temp.split(":")[0]);
        //compara se os que ja estão na lista ainda estão online
        for (int b = 0; b < lista_online.getSize(); b++) {
            for (int g = 1; g <= a; g++) {
                if (!lista_online.get(b).equals(temp.split(":")[g])) {
                    lista_online.remove(b);
                }
            }
        }
        //add na lista do cliente os novos onlines
        if (lista_online.getSize() > 0) {
            for (int b = 1; b <= a; b++) {
                for (int g = 0; g < lista_online.getSize(); g++) {
                    if (!temp.split(":")[b].equals(lista_online.get(g))) {
                        lista_online.addElement(temp.split(":")[b]);
                    }
                }
            }
        } else {
            for (int i = 1; i <= a; i++) {
                lista_online.addElement(temp.split(":")[i]);
            }
        }
    }

    private void enviaMensagem() {
        try {
            cliCon.enviaMsg("MSG:"+(String) listaPessoasOnline.getSelectedValue()+":".concat(campo_msg.getText().concat(":")));
        } catch (SocketException ex) {
            Logger.getLogger(JanelaChat.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public static void setMSG(String msg){
        areaMSGs.setText(msg);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        painel_lista = new javax.swing.JPanel();
        online = new javax.swing.JLabel();
        painel_lista1 = new javax.swing.JScrollPane();
        listaPessoasOnline = new javax.swing.JList();
        campo_msg = new javax.swing.JTextField();
        envia = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        areaMSGs = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                formMouseMoved(evt);
            }
        });

        painel_lista.setBackground(new java.awt.Color(255, 255, 255));

        online.setText("Onlines");

        listaPessoasOnline.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listaPessoasOnlineMouseClicked(evt);
            }
        });
        painel_lista1.setViewportView(listaPessoasOnline);

        campo_msg.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                campo_msgKeyPressed(evt);
            }
        });

        envia.setText("Enviar");
        envia.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                enviaActionPerformed(evt);
            }
        });

        jLabel1.setText("Mensagens :");

        jButton3.setText("Mensagem para grupo");

        jButton2.setText("Chat Privado");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        areaMSGs.setColumns(20);
        areaMSGs.setRows(5);
        jScrollPane1.setViewportView(areaMSGs);

        javax.swing.GroupLayout painel_listaLayout = new javax.swing.GroupLayout(painel_lista);
        painel_lista.setLayout(painel_listaLayout);
        painel_listaLayout.setHorizontalGroup(
            painel_listaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(painel_listaLayout.createSequentialGroup()
                .addGroup(painel_listaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(painel_listaLayout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(online))
                    .addGroup(painel_listaLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(painel_lista1, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(painel_listaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel1)
                    .addGroup(painel_listaLayout.createSequentialGroup()
                        .addGroup(painel_listaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 489, Short.MAX_VALUE)
                            .addComponent(campo_msg, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 477, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(painel_listaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButton3)
                            .addComponent(jButton2)
                            .addComponent(envia))))
                .addContainerGap(25, Short.MAX_VALUE))
        );
        painel_listaLayout.setVerticalGroup(
            painel_listaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(painel_listaLayout.createSequentialGroup()
                .addComponent(jLabel1)
                .addGap(4, 4, 4)
                .addGroup(painel_listaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, painel_listaLayout.createSequentialGroup()
                        .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton3)
                        .addGap(285, 285, 285))
                    .addGroup(painel_listaLayout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(online)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(painel_listaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 317, Short.MAX_VALUE)
                            .addComponent(painel_lista1, javax.swing.GroupLayout.DEFAULT_SIZE, 317, Short.MAX_VALUE))))
                .addGroup(painel_listaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(painel_listaLayout.createSequentialGroup()
                        .addGap(60, 60, 60)
                        .addComponent(envia)
                        .addGap(24, 24, 24))
                    .addGroup(painel_listaLayout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addComponent(campo_msg, javax.swing.GroupLayout.DEFAULT_SIZE, 68, Short.MAX_VALUE)
                        .addContainerGap())))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(painel_lista, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(painel_lista, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseMoved
        /* if(msgNova == null){
        msgNova = cliCon.recebeMSG();
        msgAnterior = msgNova;
        if(msgNova != null) areaMSGs.append(cliCon.recebeMSG().concat("\n"));
        }
        else {
        msgNova = cliCon.recebeMSG();
        if(! msgNova.equals(msgAnterior)) areaMSGs.append(cliCon.recebeMSG().concat("\n"));
        msgAnterior = msgNova;
        }*/
    }//GEN-LAST:event_formMouseMoved

    private void enviaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enviaActionPerformed
        enviaMensagem();
    }//GEN-LAST:event_enviaActionPerformed

private void listaPessoasOnlineMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listaPessoasOnlineMouseClicked
    if (evt.getClickCount() == 2) {
        String pessoa = (String) listaPessoasOnline.getSelectedValue();
        System.out.println("chat privado com : " + pessoa);
        JanelaChatPrivado chatPrivado = new JanelaChatPrivado(pessoa, cliCon);
        chatPrivado.setLocationRelativeTo(chat);
        chatPrivado.setVisible(true);
    }
}//GEN-LAST:event_listaPessoasOnlineMouseClicked

private void campo_msgKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_campo_msgKeyPressed
    if (evt.getKeyCode() == 10) {
        enviaMensagem();
    }
}//GEN-LAST:event_campo_msgKeyPressed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        if (listaPessoasOnline.getSelectedIndices().length == 1) {
            JanelaChatPrivado chatPrivado;
            chatPrivado = new JanelaChatPrivado((String) listaPessoasOnline.getSelectedValue(), cliCon);
            chatPrivado.setLocationRelativeTo(chat);
            chatPrivado.setVisible(true);
        }

    }//GEN-LAST:event_jButton2ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private static javax.swing.JTextArea areaMSGs;
    private javax.swing.JTextField campo_msg;
    private javax.swing.JButton envia;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList listaPessoasOnline;
    private javax.swing.JLabel online;
    private javax.swing.JPanel painel_lista;
    private javax.swing.JScrollPane painel_lista1;
    // End of variables declaration//GEN-END:variables
}
